<template>
  <div class="login-box">
    <div class="login-input-box">
      <h1>信贷管理系统</h1>
      <el-form
        :model="ruleForm"
        :rules="rules"
        status-icon
        ref="ruleForm"
        class="demo-ruleForm"
      >
        <el-form-item prop="username">
          <el-input
            prefix-icon="el-icon-user-solid"
            v-model="ruleForm.username"
          ></el-input>
        </el-form-item>

        <el-form-item prop="pass">
          <el-input
            prefix-icon="el-icon-s-order"
            type="password"
            v-model="ruleForm.pass"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-button type="primary" @click="submitForm">提交</el-button>
      </el-form>
    </div>
  </div>
</template>

<script>
import {doLogin} from '@/apis/user.js'
export default {
  name: "Login",
  data() {
    return {
      ruleForm: {
        username: "",
        pass: "",
      },
      rules: {
        pass: [
          {
            validator: this.validatePass,
            trigger: "blur",
          },
        ],
        username: [
          { required: true, trigger: "blur", message: "请输入用户名" },
        ],
      },
    };
  },
  methods: {
    //跳转首页
    async login(form) {
      //调用登录结构 form为登录 信息
      let res = await doLogin(form)
      
      //逻辑判断 保存token入localhost
      if(res?.data?.data?.token){
        localStorage.setItem('token',res?.data?.data?.token)
        //将用户名传入vuex
        this.$store.commit('showUserName',this.ruleForm.username)
         //在这里成功后执行这个方法，await确保成功到菜单和路由
         await this.$store.dispatch('getMenuList')
        console.log(res)
      //成功后跳转到首页
      this.$router.replace("/home");
      }else{
        this.$message.error('登录失败!!!');
      }
      
    },
    validatePass(rule, value, callback) {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else if (value.length < 6) {
        callback(new Error("密码不能小于6位数"));
      } else {
        callback();
      }
    },
    submitForm() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          // 如果验证通过，
          //调用login方法，传入登录信息，下面会定义
          this.login(this.ruleForm);
        } else {
          return false;
        }
      });
    },
  },
};
</script>

<style  lang="scss" scoped>
.login-input-box {
  width: 650px;
  height: 320px;
  background: #fff;
  text-align: center;
  padding: 40px 40px 12px 12px;
}

.login-box {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: url(../assets/bg2.jpg);
  background-size: cover;
}

.el-button {
  width: 600px;
}

.el-input {
  width: 600px;
  margin-bottom: 16px;
}

::v-deep .el-input__inner {
  background: #e5e5e5;
}
</style>